package com.gbase8c.dmt.dao.file;

import com.gbase8c.dmt.common.util.JsonMapper;
import com.gbase8c.dmt.config.DmtConfig;
import com.gbase8c.dmt.dao.DataSourceDao;
import com.gbase8c.dmt.model.migration.dto.DataSourceDto;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.List;
import java.util.Map;

public class DataSourceDaoImpl extends BasicDao<DataSourceDto> implements DataSourceDao {

    private DmtConfig dmtConfig;

    public DataSourceDaoImpl(DmtConfig dmtConfig) {
        super();
        this.dmtConfig = dmtConfig;
        mkdirs(path());
    }

    @Override
    public String path() {
        return dmtConfig.taskDir() + File.separator + "ds";
    }

    @Override
    public File file(DataSourceDto dataSourceDto) {
        String filepath = StringUtils.join(new String[] {path(), dataSourceDto.getId() + ".json"}, File.separator);
        return new File(filepath);
    }

    public DataSourceDto get(String id) {
        // add by +7 , from 2jq&yzf request
        DataSourceDto dto = super.get(id);
        init(dto);
        return dto;
    }

    private void init(DataSourceDto dto) {
        if (StringUtils.isNotBlank(dto.getPropertiesJson())) {
            Map<String, Object> ps = JsonMapper.nonEmptyMapper().fromJson(dto.getPropertiesJson(), Map.class);
            if (dto.getProperties() != null) {
                dto.getProperties().putAll(ps);
            } else {
                dto.setProperties(ps);
            }
        }
    }

    public List<DataSourceDto> list() {
        List<DataSourceDto> dtos = super.list();
        for (DataSourceDto dto : dtos) {
            init(dto);
        }
        return dtos;
    }

    @Override
    public void delete(DataSourceDto dataSourceDto) {
        delete(dataSourceDto.getId());
    }

    @Override
    public void preSave(String id, DataSourceDto dataSourceDto) {
        dataSourceDto.setId(id);
        if (dataSourceDto.getProperties() != null && !dataSourceDto.getProperties().isEmpty()) {
            String json = JsonMapper.nonNullMapper().toJson(dataSourceDto.getProperties());
            dataSourceDto.setPropertiesJson(json);
        }
    }

}
